package com.cs.beneficios.web.action;
import com.cs.beneficios.business.entity.AtributosDAO;
import com.cs.beneficios.business.entity.ProgramaDAO;
import com.cs.beneficios.business.entity.SubProgramaDAO;
import com.cs.beneficios.business.model.ProgramaVO;
//import com.cs.beneficios.business.model.SubProgramaVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.beneficios.common.entity.Consultas;
import com.cs.beneficios.validator.Validaciones;
import com.cs.beneficios.web.form.SubprogramaForm;
import com.cs.paoyer.administration.business.model.UserVO;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

//import java.sql.Connection;
//import java.sql.ResultSet;
import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class GuardarSubprogramaAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
  
     ActionMessages messages = new ActionMessages();
     try{
      	AccessControl access = new AccessControl();
        access.validateAccess(mapping,request,response);
        //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
		ConnectionFactory cf = new ConnectionFactory();
        SubprogramaForm objSubForm = (SubprogramaForm) form;
        HttpSession session = request.getSession();
        
        
        try{
            // Proceso para validar si el usuario tiene permisos para crear el beneficio.
            UserVO objUservo = (UserVO) request.getSession().getAttribute("userInfo");
            Long lnCodeUser = objUservo.getCode();
            String strNameGroup = objUservo.getUserGroupName();
            
            String strCodeProg = request.getParameter("programa1");
            ProgramaVO objProgVo = new ProgramaVO();
            objProgVo.setCodePrograma(strCodeProg);
            
            ProgramaDAO objProgDao = new ProgramaDAO(cf);
            Collection cPrograma = null;
            cPrograma = objProgDao.findProgramaByCriterea(objProgVo, strNameGroup, lnCodeUser, objUservo.getCodeArea());  
            cf.closeConnection(objProgDao.getConn());
            //Fin del proceso
            
             if (cPrograma != null && cPrograma.size() != 0)
             {
                 Validaciones validacion = new Validaciones(cf);
                 boolean existe=false;
                 
                 if (objSubForm.getSubprograma() != null && objSubForm.getCodePrograma() != null){
                    existe = validacion.validasubprg(objSubForm.getSubprograma().trim());
                    cf.closeConnection(validacion.getConn());
                 }
                 
                 if(!existe){  
                      //Proceso para la auditoria
                      UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
                      String terminalAddress = request.getRemoteAddr();
                      String strTerminal = ("WEB="+terminalAddress);
                      Calendar c = Calendar.getInstance(); 
                      SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
                      //Fin del proceso
                      
                      String strDesde = objSubForm.getDesde();
                      String strHasta = objSubForm.getHasta();
                      
                      String ArrFecha[] =strDesde.split("-");
                      String strDay = null;
                      String strMonth = null;
                      String strYear = null;
                      String strDesdeFinal = null;
                      String strHastaFinal = null;
                      
                      strDay = ArrFecha[2];
                      strMonth = ArrFecha[1];                       
                      strYear = ArrFecha[0];
                      strDesdeFinal = strDay+"/"+strMonth+"/"+strYear;
                      
                     String ArrFecha2[] =strHasta.split("-");
                     strDay = ArrFecha2[2];
                     strMonth = ArrFecha2[1];                       
                     strYear = ArrFecha2[0];
                     strHastaFinal = strDay+"/"+strMonth+"/"+strYear;
                      
                     objSubForm.setDesde(strDesdeFinal);
                     objSubForm.setHasta(strHastaFinal);
                     
                     
                      SubProgramaDAO objSubproDAO = new SubProgramaDAO(cf);
                      int iOutput = objSubproDAO.InsertBeneficio(objSubForm,user.getName(),strTerminal,dateFormat.format(c.getTime()));
                      String strMaxCode = null; 
                      
                      if(iOutput > 0)
                      {
                        session.setAttribute("mensajes","El subprograma fue creado satisfactoriamente.");
                        strMaxCode = objSubproDAO.getMaxCode();
                        session.setAttribute("subpro",strMaxCode);
                        if(strMaxCode != null)
                        {
                            // Proceso para obtener el c�digo de los atributos gen�ricos
                            AtributosDAO objAtriDAO = new AtributosDAO(cf);
                            String strCodeAtri = objAtriDAO.getCodeAtributoGenerico("DESPLAZADO");
                            cf.closeConnection(objAtriDAO.getConn());
                            // Fin del proceso
                            
                             // Proceso para insertar los atributos obligatorios
                             String strArr2[] = {user.getName(), dateFormat.format(c.getTime()),strTerminal,user.getName(),dateFormat.format(c.getTime()),strTerminal};
                             Consultas objCons = new Consultas(cf);
                             int InsertAtriGenerico= objCons.InsertAtributoGenerico(strCodeAtri,strMaxCode,strArr2);
                             cf.closeConnection(objCons.getConn());
                             // Fin del Proceso
                        }
                      }else{
                          session.setAttribute("mensajes","El Beneficio no se pudo crear.");
                      }
                      
                      cf.closeConnection(objSubproDAO.getConn());
                 }else{
                     session.setAttribute("mensajes","El Beneficio ya existe...!!!");
                     request.setAttribute("secretaria",objSubForm.getSubsecretaria());
                     return mapping.findForward("fail");
                 }
             }else{
                 response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
             }
            
            
            
        }catch (SQLException e){
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
            session.setAttribute("mensajes","El Beneficio no se pudo crear.");
        }
     }catch(UserException ue){
        messages.add("msgWarn",  new ActionMessage("loginForm.message."
																			+ ue.getExceptionVO().getId()));
	saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
      
   }
    return mapping.findForward("success");
  }
}